package edu.suda.scratcher.ippgserver.servlet;

import java.io.*;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import org.apache.ibatis.session.SqlSession;
import edu.suda.scratcher.ippgserver.mapper.*;
import edu.suda.scratcher.ippgserver.beans.Record;

@WebServlet("/actions/add_record")
public class AddRecord extends Action {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/plain");       
        HttpSession httpSession = request.getSession(true);
        Writer writer = response.getWriter();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        RecordMapper mapper = sqlSession.getMapper(RecordMapper.class);
        
        Record record = new Record();
        
        try {
            record.setUsername((String)httpSession.getAttribute("username"));
            record.setHr(Double.parseDouble(request.getParameter("hr")));
            record.setSpo(Double.parseDouble(request.getParameter("spo")));
            record.setRtime(Timestamp.valueOf(LocalDateTime.now()));
            mapper.addRecord(record);
            sqlSession.commit();
            writer.write("ok");
        } catch (Exception ex) {
            writer.write("err");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    
}
